package com.example.trigger.http;

import com.example.domain.strategy.model.entity.RaffleAwardEntity;
import com.example.domain.strategy.model.entity.RaffleFactorEntity;
import com.example.domain.strategy.model.entity.StrategyAwardEntity;
import com.example.domain.strategy.service.IRaffleAward;
import com.example.domain.strategy.service.IRaffleStrategy;
import com.example.domain.strategy.service.armory.IStrategyArmory;
import com.example.trigger.api.IRaffleService;
import com.example.trigger.api.dto.RaffleAwardListRequestDTO;
import com.example.trigger.api.dto.RaffleAwardListResponseDTO;
import com.example.trigger.api.dto.RaffleRequestDTO;
import com.example.trigger.api.dto.RaffleResponseDTO;
import com.example.types.enums.ResponseCode;
import com.example.types.exception.AppException;
import com.example.types.model.Response;
import com.alibaba.fastjson.JSON;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: 三石
 * @desc: 抽奖接口实现， 也是暴露给外部的controller
 * @Date: 2024-07-27-15:53
 */
@Slf4j
@AllArgsConstructor
@RequestMapping("/raffle/")
@RestController("raffle_controller")
@CrossOrigin("${app.config.cross-origin}")
public class RaffleController implements IRaffleService {

    /** 策略装配 */
    private final IStrategyArmory strategyArmory;

    /** 策略奖品相关 */
    private final IRaffleAward raffleAward;

    /** 抽奖策略相关 */
    private final IRaffleStrategy raffleStrategy;

    /**
     * 策略装配接口
     * <a href="http://localhost:8089/api/v1/raffle/strategy_armory">/api/v1/raffle/strategy_armory</a>
     *
     * @param strategyId 策略ID
     * @return 装配结果
     */
    @Override
    @RequestMapping(value = "strategy_armory", method = RequestMethod.GET)
    public Response<Boolean> strategyArmory(Long strategyId) {
        try {
            log.info("策略装配开始, strategyId: {}", strategyId);
            boolean armoryStatus = strategyArmory.assembleLotteryStrategy(strategyId);
            Response<Boolean> response = Response.<Boolean>builder()
                    .code(ResponseCode.SUCCESS.getCode())
                    .info(ResponseCode.SUCCESS.getInfo())
                    .data(armoryStatus)
                    .build();
            log.info("策略装配结束, strategyId: {} armoryStatus: {}", strategyId, armoryStatus);
            return response;

        } catch (Exception e) {
            log.error("策略装配失败, strategyId: {}", strategyId, e);
            return Response.<Boolean>builder()
                    .code(ResponseCode.UN_ERROR.getCode())
                    .info(ResponseCode.UN_ERROR.getInfo())
                    .build();
        }
    }

    /**
     * 查询奖品列表
     * <a href="http://localhost:8089/api/v1/raffle/query_raffle_award_list">/api/v1/raffle/query_raffle_award_list</a>
     *
     * @param raffleAwardListRequestDTO 参数 {"strategyId":1000001}
     * @return 奖品列表
     */
    @Override
    @RequestMapping(value = "query_raffle_award_list", method = RequestMethod.POST)
    public Response<List<RaffleAwardListResponseDTO>> queryRaffleAwardList(@RequestBody RaffleAwardListRequestDTO raffleAwardListRequestDTO) {
        try {
            log.info("查询策略奖品列表开始, strategyId: {}", raffleAwardListRequestDTO.getStrategyId());
            // 查询奖品列表
            List<StrategyAwardEntity> strategyAwardEntities =
                    raffleAward.queryRaffleStrategyAwardList(raffleAwardListRequestDTO.getStrategyId());
            // 类型转换
            List<RaffleAwardListResponseDTO> raffleAwardListResponseDTOS = new ArrayList<>();
            for (StrategyAwardEntity strategyAwardEntity : strategyAwardEntities) {
                raffleAwardListResponseDTOS.add(
                        RaffleAwardListResponseDTO.builder()
                                .awardId(strategyAwardEntity.getAwardId())
                                .awardTitle(strategyAwardEntity.getAwardTitle())
                                .awardSubtitle(strategyAwardEntity.getAwardSubtitle())
                                .sort(strategyAwardEntity.getSort())
                                .build()
                );
            }
            // 构造返回结果
            Response<List<RaffleAwardListResponseDTO>> response = Response.<List<RaffleAwardListResponseDTO>>builder()
                    .code(ResponseCode.SUCCESS.getCode())
                    .info(ResponseCode.SUCCESS.getInfo())
                    .data(raffleAwardListResponseDTOS)
                    .build();
            log.info("查询策略奖品列表结束, strategyId: {}", raffleAwardListRequestDTO.getStrategyId());
            return response;

        } catch (Exception e) {
            log.error("查询策略奖品列表失败, strategyId: {}", raffleAwardListRequestDTO.getStrategyId(), e);
            throw new RuntimeException(e);
//            return Response.<List<RaffleAwardListResponseDTO>>builder()
//                    .code(ResponseCode.UN_ERROR.getCode())
//                    .info(ResponseCode.UN_ERROR.getInfo())
//                    .build();
        }
    }

    /**
     * 随机抽奖接口
     * <a href="http://localhost:8091/api/v1/raffle/random_raffle">/api/v1/raffle/random_raffle</a>
     *
     * @param requestDTO 请求参数 {"strategyId":1000001}
     * @return 奖品信息
     */
    @Override
    @RequestMapping(value = "random_raffle", method = RequestMethod.POST)
    public Response<RaffleResponseDTO> randomRaffle(@RequestBody RaffleRequestDTO requestDTO) {
        try {
            log.info("随机抽奖开始 strategyId: {}", requestDTO.getStrategyId());
            // 调用抽奖接口
            RaffleAwardEntity raffleAwardEntity = raffleStrategy.preformRaffle(RaffleFactorEntity.builder()
                    .userId("system")
                    .strategyId(requestDTO.getStrategyId())
                    .build());
            // 封装返回结果
            Response<RaffleResponseDTO> response = Response.<RaffleResponseDTO>builder()
                    .code(ResponseCode.SUCCESS.getCode())
                    .info(ResponseCode.SUCCESS.getInfo())
                    .data(RaffleResponseDTO.builder()
                            .awardId(raffleAwardEntity.getAwardId())
                            .awardIndex(raffleAwardEntity.getSort())
                            .build())
                    .build();
            log.info("随机抽奖完成 strategyId: {} response: {}", requestDTO.getStrategyId(), JSON.toJSONString(response));
            return response;
        } catch (AppException e) {
            log.error("随机抽奖失败 strategyId：{} {}", requestDTO.getStrategyId(), e.getInfo());
            return Response.<RaffleResponseDTO>builder()
                    .code(e.getCode())
                    .info(e.getInfo())
                    .build();
        } catch (Exception e) {
            log.error("随机抽奖失败 strategyId：{}", requestDTO.getStrategyId(), e);
            return Response.<RaffleResponseDTO>builder()
                    .code(ResponseCode.UN_ERROR.getCode())
                    .info(ResponseCode.UN_ERROR.getInfo())
                    .build();
        }
    }

}
